import { defineStore } from "pinia";
import { store } from "@/store";
import { LoginInfo } from "@/api/admin/login/types";
import router from "@/router";
import { useTagsViewStore } from "./tagsView";
import { deepClone } from "@/utils";
// import { userApi } from "@/api/admin/user";

interface User {
  // 用户信息，登录时从后端获取的用户信息
  userInfo?: any;
  // 用户权限元数据
  // permissionsMeta: any[];
  // token 键名
  tokenKey: string;
  // 短token
  access_token: string;
  // 长token
  refresh_token: string;
  // 是否记住密码
  rememberMe: boolean;
  // 角色路由,从后端获取的当前角色的路由
  roleRouters?: any[];
  // 登录信息,为用户名和密码，为了登录记住密码，下次退出登录时不用再输入
  loginInfo?: LoginInfo;
  // 角色信息
  userRoles: any[]
}

export const useUserStore = defineStore("user", {
  state: (): User => {
    return {
      userInfo: undefined,
      userRoles: [],
      tokenKey: "Authorization",
      access_token: "",
      refresh_token: "",
      rememberMe: false,
      roleRouters: undefined,
      loginInfo: undefined
    }
  },
  getters: {
    getPermissions(state) {
      let permissions: any[] = []

      state.userRoles.forEach((role: any) => {
        permissions = permissions.concat(role.permission)
      })
      return deepClone(permissions)
    },
    getUserRoles(state) {
      return state.userRoles
    },
    getUserInfo(state) {
      return state.userInfo
    },
    getAccessToken(state) {
      return state.access_token
    },
    getRefreshToken(state) {
      return state.refresh_token
    },
    getRememberMe(state) {
      return state.rememberMe
    },
    getLoginInfo(state) {
      return state.loginInfo
    },
    getRoleRouters(state) {
      return state.roleRouters
    },
    getTokenKey(state) {
      return state.tokenKey
    }
  },
  actions: {
    setTokenKey(tokenKey: string) {
      this.tokenKey = tokenKey
    },
    setAccessToken(access_token: string) {
      this.access_token = access_token
    },
    setRefreshToken(refresh_token: string) {
      this.refresh_token = refresh_token
    },
    setUserInfo(userInfo?: any) {
      this.userInfo = userInfo
    },
    setUserRoles(userRoles: any) {
      this.userRoles = userRoles
    },
    setLoginInfo(loginInfo?: LoginInfo) {
      this.loginInfo = loginInfo
    },
    setRoleRouters(roleRouters: any) {
      this.roleRouters = roleRouters
    },
    reset() {
      const tagsViewStore = useTagsViewStore()
      tagsViewStore.removeAllViews()
      this.roleRouters = undefined
      this.access_token = ""
      this.refresh_token = ""
      this.userInfo = undefined
      router.replace("/login")
    },

    // 退出登录
    logout() {
      this.reset()
    }
  },
  persist: {
    omit: ['userRoles'],
  },
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}